﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HCQ2_IDAL;
using HCQ2_Model;
using HCQ2_Model.SysModel;
using HCQ2_Common.SQL;
using System.Data;
using HCQ2_Common;

namespace HCQ2_DAL_MSSQL
{
    /// <summary>
    ///  登录记录数据层实现
    /// </summary>
    public partial class T_LoginDAL:  IT_LoginDAL
    {
        /// <summary>
        ///  登录成功时编辑
        /// </summary>
        /// <param name="login">登录记录对象</param>
        /// <returns></returns>
        public int EditLoginByOk(T_Login login)
        {
            return base.Modify(login, s => s.user_id == login.user_id, "login_count", "error_count", "login_time",
                "login_ip", "last_time", "last_ip", "if_false", "source");
        }
        /// <summary>
        ///  登录失败时编辑
        /// </summary>
        /// <param name="login">登录记录对象</param>
        /// <returns></returns>
        public int EditLoginByError(T_Login login)
        {
            return base.Modify(login, s => s.user_id == login.user_id, "error_count", "login_time", "login_ip",
                "if_false", "note", "source");
        }
        /// <summary>
        ///  添加登录记录
        /// </summary>
        /// <param name="login">登录记录对象</param>
        /// <returns></returns>
        public int AddLoginInfo(T_Login login)
        {
            return base.Add(login);
        }
        /// <summary>
        ///  获取登录日志
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <param name="orgUnit">单位</param>
        /// <param name="page">第几页</param>
        /// <param name="size">每页数</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public List<UserLoginLog> GetLoginLogData(string keyword, string orgUnit, int page, int size, int status, string loginSource, string orderColumn, string orderType, out int total)
        {
            sb?.Clear();
            string sql = $"SELECT  TOP {size} logins.*,users.user_name,users.login_name,users.user_unit ";
            sb.Append($@" FROM 
            (SELECT user_id,user_name,login_name,user_unit,unit_code FROM dbo.T_User)users INNER JOIN
            (SELECT user_id,login_count,source,CONVERT(varchar(100),login_time,20)as login_time,CONVERT(varchar(100),last_time,20)AS last_time,
            rowNum=ROW_NUMBER() OVER(ORDER BY {orderColumn} {orderType}),
            status=(CASE WHEN source='app' AND pro_type='VCircle' THEN 
				(SELECT (CASE WHEN user_status<>1 THEN 0 ELSE 1 END) FROM dbo.T_User u WHERE u.user_id=T_Login.user_id)
				WHEN ISNULL(last_time,0)=0 THEN 0 
				WHEN DATEDIFF(MINUTE,last_time,GETDATE())>60 THEN 0 ELSE 1 END)
             FROM dbo.T_Login)logins ON logins.user_id = users.user_id
             WHERE 1=1 ");
            //关键字
            if (!string.IsNullOrEmpty(keyword))
                sb.Append($" AND (users.login_name LIKE '%{keyword}%' OR users.user_name LIKE '%{keyword}%') ");
            //单位
            if (!string.IsNullOrEmpty(orgUnit))
                sb.Append($" AND users.unit_code='{orgUnit}' ");
            //状态
            if (status > -1)
                sb.Append($" AND logins.status={status} ");
            //登录来源
            if(!string.IsNullOrEmpty(loginSource))
                sb.Append($" AND logins.source='{loginSource}' ");
            //数量
            total = Helper.ToInt(SqlHelper.ExecuteScalar("SELECT COUNT(0)AS num " + sb.ToString()));
            DataTable dt = SqlHelper.ExecuteDataTable(sql+sb.ToString()+ " ORDER BY logins.rowNum ASC ");
            return HCQ2_Common.Data.DataTableHelper.DataTableToIList<UserLoginLog>(dt);
        }
        /// <summary>
        ///  获取登录详情
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public List<LoginDetialModel> GetLoginDetialList(int user_id, int page, int size,out int total)
        {
            sb?.Clear();
            sb.Append($@"  
             (SELECT user_id,ROW_NUMBER() OVER(ORDER BY login_date DESC)AS num,source,CONVERT(varchar(100),login_date,20)AS login_date FROM dbo.T_LoginLog WHERE user_id={user_id})logs INNER JOIN
             (SELECT user_id,user_name,login_name FROM dbo.T_User WHERE user_id={user_id})users ON users.user_id = logs.user_id");
            total = Helper.ToInt(SqlHelper.ExecuteScalar("SELECT COUNT(0)AS num  FROM " + sb.ToString()));
            DataTable dt = SqlHelper.ExecuteDataTable($@"SELECT TOP {size} logs.*,users.user_name,users.login_name FROM " +sb.ToString()+$" WHERE logs.num>{(page - 1) * size}");
            return HCQ2_Common.Data.DataTableHelper.DataTableToIList<LoginDetialModel>(dt);
        }
        /// <summary>
        ///  获取最后一次登录code
        /// </summary>
        public string GetLoginLogCode(int user_id)
        {
            sb?.Clear();
            sb.Append($@"SELECT  TOP 1 log_code FROM dbo.T_LoginLog WHERE user_id={user_id} ORDER BY login_date DESC;");
            return Helper.ToString(SqlHelper.ExecuteScalar(sb.ToString()));
        }
    }
}
